// import { legacy_createStore as createStore } from 'redux'
import {
  configureStore, // 用于创建仓库
  createSlice, // 创建切片
} from './@reduxjs/toolkit'
import logger from 'redux-logger'

const counter1Slice = createSlice({
  name: "counter1",
  initialState: { number: 0 },
  reducers: {
    add: state => ({ number: state.number + 1 }),
    minus: (state, action) => ({ number: state.number - action.payload })
  }
})
const {
  add: add1,
  minus: minus1,
} = counter1Slice.actions
console.log('counter1Slice', counter1Slice)
console.log('add1的返回值', add1())

const counter2Slice = createSlice({
  name: "counter2",
  initialState: { number: 0 },
  reducers: {
    add: state => ({ number: state.number + 1 }),
    minus: (state, action) => ({ number: state.number - action.payload })
  }
})
const {
  add: add2,
  minus: minus2,
} = counter2Slice.actions
// const store = createStore(reducer)
const store = configureStore({
  reducer: {
    [counter1Slice.reducerPath]: counter1Slice.reducer,
    [counter2Slice.reducerPath]: counter2Slice.reducer,
  },
  middleware: defaultMiddlewares => [...defaultMiddlewares(), logger], // 合并内置中间件
  preloadedState: {
    [counter1Slice.reducerPath]: {number: 0},
    [counter2Slice.reducerPath]: {number: 0}
  },
})

let valueEl1 = document.getElementById('value1')
function render1() {
  valueEl1.innerHTML = store.getState().counter1.number
}
render1()

store.subscribe(render1)
let valueEl2 = document.getElementById('value2')
function render2() {
  valueEl2.innerHTML = store.getState().counter2.number
}
render2()

store.subscribe(render2)

document.getElementById('add1').addEventListener('click', () => store.dispatch(add1()))

document.getElementById('minus1').addEventListener('click', () => store.dispatch(minus1(2)))

document.getElementById('add2').addEventListener('click', () => store.dispatch(add2()))

document.getElementById('minus2').addEventListener('click', () => store.dispatch(minus2(2)))

